
<template>
  <div class='tag-dialog'>
      <el-dialog width="400px" :visible.sync="showDialog" :title="`${data.id?'修改目录':'新增目录'}`" @close="showDialog = false">
        <!-- 表单内容 -->
        <el-form ref="form" :model="formModel" :rules="rules" label-width="80px">
            <el-form-item label="所属学科" v-if="!$route.query.id" prop="subjectID">
              <el-select style="width: 280px" v-model="formModel.subjectID">
                <el-option v-for="items in list" :key="items.value" :label="items.label" :value="items.value" />
              </el-select>
            </el-form-item>
          <el-form-item label="目录名称" prop="tagName">
            <el-input v-model="formModel.tagName" placeholder="请输入目录名称" />
          </el-form-item>
        </el-form>
        <div slot="footer">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button @click="confirm()" type="primary">确认</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/tags.js'
import { simple } from '@/api/hmmm/subjects.js'
export default {
  name: 'tagsAdd',
  props: {
    data: {
      default: () => {},
      type: Object
    }
  },
  data () {
    return {
      list: [],
      showDialog: false,
      formModel: {
        id: null,
        tagName: null,
        subjectID: null
      },
      rules: {
        tagName: [
          { required: true, message: '请输入目录名称', tirgger: 'blur' }
        ]
      }
    }
  },
  async created () {
    const { data: subjectArr } = await simple()
    this.list = subjectArr
  },
  methods: {
    open () {
      this.showDialog = true
      if (this.data.id) {
        const { id, tagName, subjectID } = this.data
        this.formModel = { id, tagName, subjectID }
      } else {
        this.formModel = {
          id: null,
          tagName: null,
          subjectID: +this.$route.query.id || null
        }
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    async confirm () {
      this.$refs.form.validate(async boo => {
        if (!boo) return

        if (!this.data.id) {
          // 新增
          await add(this.formModel)
        } else {
          // 修改
          this.formModel.id = this.data.id
          await update(this.formModel)
        }
        this.$message.success(this.data.id ? '编辑目录成功' : '新增目录成功')
        this.showDialog = false
        this.$emit('handleTag')
      })
    }
  }
}
</script>

<style scoped lang='scss'></style>
